package com.zat.mes.andrmes.dofun.system

import android.content.DialogInterface
import android.util.Log
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.bigkoo.pickerview.view.TimePickerView
import com.contrarywind.view.WheelView
import com.google.gson.Gson
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.data.ClockBean
import com.zat.mes.andrmes.data.LoginResultBean
import com.zat.mes.andrmes.dofun.system.adapter.ClockAdapter
import com.zat.mes.andrmes.dofun.system.vm.ClockViewModel
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.itemdecoration.TimeItemDecoration
import com.zat.mes.andrmes.utils.DateUtil
import com.zat.mes.andrmes.utils.GlideUtil
import com.zat.mes.andrmes.utils.PreferencesUtil
import com.zat.mes.andrmes.utils.showToast
import kotlinx.android.synthetic.main.activity_clock_in.*
import kotlinx.android.synthetic.main.layout_head_clock.*
import kotlinx.android.synthetic.main.layout_title.*
import java.util.*


/**
 * 签到打卡
 */
class ClockInActivity : BaseActivity(), View.OnClickListener, ClockAdapter.ItemChildClickListener {


    private var timePicker: TimePickerView? = null
    var clockAdapter: ClockAdapter? = null
    var selectedDate = DateUtil.formatDate(Date(), DateUtil.FORMAT_3)
    var showDate: String? = null
    var empId: Long? = null
    var empName: String? = null
    private lateinit var clockModel: ClockViewModel
    override fun init() {
        initView()
        initData()
        loadModel()
    }

    /**
     * 初始化数据
     */
    private fun initData() {
        val loginResultBean = Gson().fromJson(
            PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
            LoginResultBean::class.java
        )
        empId = loginResultBean.empid
        empName = loginResultBean.empname
        tvNameClock.text = loginResultBean.empname
        GlideUtil.setHeader(this, loginResultBean?.img, ivHeadClock)
        showDate =
            DateUtil.formatDate(Date(), getString(R.string.head_date)) + DateUtil.getWeek(Date())
        setDateText()


        initDatePick()
        clockAdapter = ClockAdapter(R.layout.item_recyler_clock, this)
        recylerClock.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        recylerClock.addItemDecoration(TimeItemDecoration(this))
        recylerClock.adapter = clockAdapter
    }

    /**
     * 初始化 viewmodel
     */
    private fun loadModel() {
        showLoading()
        clockModel = ViewModelProvider(this).get(ClockViewModel::class.java)
        clockModel.getClockList().observe(this, androidx.lifecycle.Observer {
            Log.e("clock", "几次")
            closeLoading()
            if (it != null && it?.size > 0) {
                setEmptyGone()
            } else {
                setEmptyVisible()
            }
            clockAdapter?.setNewData(it as MutableList<ClockBean>?)
        })
        loadClockList()

        //删除信息
        clockModel.getClockDel().observe(this, androidx.lifecycle.Observer {
            closeLoading()
            showToast(it)
            loadClockList()
        })

        //签到签退，日期是今天
        clockModel.getClockInOut().observe(this, androidx.lifecycle.Observer {
            closeLoading()
            showToast(it)
            btnOutClock.postDelayed(Runnable { loadClockList() }, 500)


        })
    }

    /**
     * 查询签到列表
     */
    private fun loadClockList() {
        empId?.let { clockModel.loadClockList(selectedDate, it) }
    }

    /**
     * 初始化 view
     */
    private fun initView() {
        setContentView(R.layout.activity_clock_in)
        tVtitle.text = getString(R.string.sign)

        rlRight.visibility = View.GONE
        rlReturnTitle.visibility = View.VISIBLE
        rlReturnTitle.setOnClickListener(this)
        btnInClock.setOnClickListener(this)
        btnOutClock.setOnClickListener(this)
        llCalenClock.setOnClickListener(this)


    }

    /**
     * 设置时间
     */
    fun setDateText() {
        tvCanlendarClock.text = showDate
    }

    /**
     * 初始化 时间选择器
     */
    private fun initDatePick() {
        val startCalendar = Calendar.getInstance()
        startCalendar.set(1900, 0, 1)
        val endCalendar = Calendar.getInstance()
        endCalendar.time = Date();
        timePicker = TimePickerBuilder(this, object : OnTimeSelectListener {
            override fun onTimeSelect(date: Date?, v: View?) {
                if (date != null) {
                    selectedDate = DateUtil.formatDate(date, DateUtil.FORMAT_3)
                    showDate =
                        DateUtil.formatDate(date, getString(R.string.head_date)) + DateUtil.getWeek(
                            date
                        )
                    setDateText()
                    showLoading()
                    loadClockList()
                }
            }

        }).setSubmitColor(ContextCompat.getColor(this, R.color.color_text_nomal))
            .setCancelColor(ContextCompat.getColor(this, R.color.color_text_nomal))
            .setTitleBgColor(ContextCompat.getColor(this, R.color.color_white))
            .setContentTextSize(18)
            .setLabel("", "", "", "", "", "")
            .setDividerType(WheelView.DividerType.WRAP)
            .setDividerColor(ContextCompat.getColor(this, R.color.color_theme))
            .setLineSpacingMultiplier(2.0f)
            .setRangDate(startCalendar, endCalendar)
            .setDate(endCalendar)
            .build()
    }

    override fun onClick(v: View?) {
        when (v) {
            rlReturnTitle -> finish()
            llCalenClock -> {
                timePicker?.show()

            }
            btnInClock -> {
                //签到
                showLoading()
                empId?.let { empName?.let { it1 -> clockModel.loadInOut(it, it1, "1") } }
            }
            btnOutClock -> {
                //签退
                showLoading()
                empId?.let { empName?.let { it1 -> clockModel.loadInOut(it, it1, "2") } }
            }

        }
    }

    override fun onClick(bean: ClockBean) {

        val alert = AlertDialog.Builder(this)
            .setMessage(getString(R.string.clock_in_delete_content))
            .setNegativeButton(getString(R.string.no), null)
            .setPositiveButton(
                getString(R.string.yes),
                DialogInterface.OnClickListener { dialog, which ->
                    clockModel.loadDel(bean.workId)
                    showLoading()
                })
            .show()


    }


}
